//
//  HZMallFindViewController.m
//  app
//
//  Created by 刘华舟 on 15/5/19.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZMallFindViewController.h"
#import "HZMallSearchViewController.h"
#import "HZGoodsSalesViewController.h"
#import "SNWXVoiceTestViewController.h"
#import "HZGoodsDetailViewController.h"
#import "HZMallGoodsTemaiListViewController.h"

#import "HZImageSourceConstant.h"
//categories
#import "UIImage+Conveniently.h"
#import "NSDictionary+SafetyGet.h"
//views
#import "HZGoodsFindCategoriesBar.h"
#import "HZGoodsCategoryColCell.h"
#import "HZGoodsCategoryColHeadView.h"
#import "HZCollectionView.h"

//models
#import "HZRemoteResult.h"
#import "HZFindCategoriesData.h"

//tools
#import "HZMallHttpManager.h"
#import "HZMallSqlDataManager.h"

static const CGFloat kMallHomeLabelHeight = 30;
static const CGFloat kMallHomeMargin = 20;
static NSString * const kMallSearchText = @" 搜索商品";



@interface HZMallFindViewController()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (strong, nonatomic) UILabel *searchLabel;
@property (strong, nonatomic) UIButton *voiceBtn;
@property (strong, nonatomic) UIButton *backBtn;


@property (strong, nonatomic) HZGoodsFindCategoriesBar *categoriesBar;

@property (strong, nonatomic) HZCollectionView *collectionView;
@property (strong, nonatomic) UICollectionViewFlowLayout *layout;


@property (strong, nonatomic) HZFindCategoriesData *data;
@property (strong, nonatomic) HZRemoteResult *remoteResult;

/** 是否已经停止了转菊花*/
@property (nonatomic, assign) BOOL notingViewActiveStop;

@end

@implementation HZMallFindViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor = HZ_MALL_MAIN_THEME_WHITE;
    
    self.title = @"商品分类";
    
    //label
    self.searchLabel = [[UILabel alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT ox:kMallHomeMargin fy:UB_TOP oy:self.navigationAndStatusBarHeight+10],
                                                               [self.ubo fw:UB_WIDTH ow:-2*kMallHomeMargin oh:kMallHomeLabelHeight])];
    self.searchLabel.textAlignment = NSTextAlignmentCenter;
    self.searchLabel.backgroundColor = [HZ_WHITE_COLOR colorWithAlphaComponent:1.0f];
    
    self.searchLabel.layer.masksToBounds = YES;
    self.searchLabel.layer.cornerRadius = [self.ubo uw:4];
    self.searchLabel.layer.borderColor = HZ_MALL_BORDER_LINE_GRAY_COLOR.CGColor;
    self.searchLabel.layer.borderWidth = [self.ubo pw:1];
    
    NSTextAttachment * textAttachment = [[NSTextAttachment alloc] init];//添加附件,图片
    
    UIImage *image = [UIImage imageNamed:kImageMallHomeSearch];
    
    textAttachment.image = image;
    
    textAttachment.bounds = CGRectMake(0, -2.5, image.size.height , image.size.width);
    
    NSAttributedString *imgString = [NSMutableAttributedString attributedStringWithAttachment:textAttachment];
    
    NSString *serachText = [SNUniteUrl shareUniteUrl].searchBoxText;
    if (!serachText.length) {
        serachText = kMallSearchText;
    }else{
        serachText = [NSString stringWithFormat:@" %@", serachText];
    }
    
    NSMutableAttributedString *atrString = [[NSMutableAttributedString alloc] initWithString:serachText];
    [atrString addAttribute:NSForegroundColorAttributeName value:HZ_MALL_TEXT_M_LIGHTGRAY_COLOR range:NSMakeRange(0, serachText.length)];
    [atrString addAttribute:NSFontAttributeName value:kHZFont_Content_M range:NSMakeRange(0, serachText.length)];
    [atrString insertAttributedString:imgString atIndex:0];
    
    self.searchLabel.attributedText = atrString;
    
    UITapGestureRecognizer *tapGestr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchViewOnClick)];
    [self.searchLabel addGestureRecognizer:tapGestr];
    self.searchLabel.userInteractionEnabled = YES;
    
    //voiceBtn
    self.voiceBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.searchLabel.ubo fx:UB_RIGHT ox:-kMallHomeLabelHeight fy:UB_TOP],
                                                             [self.searchLabel.ubo ow:kMallHomeLabelHeight oh:kMallHomeLabelHeight])];
    [self.voiceBtn setImage:[UIImage imageNamed:kImageMallHomeVoice] forState:UIControlStateNormal];
    self.voiceBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.voiceBtn addTarget:self action:@selector(voiceBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.searchLabel addSubview:self.voiceBtn];
    
    [self.view addSubview:self.searchLabel];
    
    
    //backBtn
    self.backBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP],
                                                            [self.ubo ow:40 oh:40])];
    [self.backBtn setImage:[UIImage imageNamed:kImageMallArrowBackReturnRed] forState:UIControlStateNormal];
    self.backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
    
    
    
    //分类列表bar
    self.categoriesBar = [[HZGoodsFindCategoriesBar alloc] initWithFrame:CGRectOf([UBO_SCREEN fx:UB_LEFT fy:UB_TOP oy:self.navigationAndStatusBarHeight+kMallHomeLabelHeight+20],
                                                                                  [UBO_SCREEN uw:kGoodsFindCategoriesBarWidth fh:UB_HEIGHT oh:-self.navigationAndStatusBarHeight-kMallHomeLabelHeight-20])];
    self.categoriesBar.tabSelectedCaller = [UBTargetCaller of:self action:@selector(switchGoodsCategory:)];
    [self.view addSubview:self.categoriesBar];
    
    
    //collectionView
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    //定义每个cell的高度和宽度
    self.layout.itemSize = [self.ubo uw:kGoodsCategoryColCellWidth uh:kGoodsCategoryColCellHeight];
    //定义cell相对section上左下右的边距(某个section中cell的边界范围)
    self.layout.sectionInset = UIEdgeInsetsMake([self.ubo uw:0], [self.ubo uw:kGoodsCategoryColCellMargin], [self.ubo uw:kGoodsCategoryColCellMargin], [self.ubo uw:kGoodsCategoryColCellMargin]);
    //定义水平间每行的最小距离(每行的最小间距)
    self.layout.minimumLineSpacing = [self.ubo uw:kGoodsCategoryColCellPadding];
    //定义一行中相邻cell间的最小间距(每行内部cell item的最小间距)
    self.layout.minimumInteritemSpacing = [self.ubo uw:kGoodsCategoryColCellPadding/2];
    //定义滚动方向
    self.layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //定义section高度和宽度
    self.layout.headerReferenceSize = [self.ubo fw:UB_WIDTH uw:-kGoodsFindCategoriesBarWidth uh:20];
    
    self.collectionView = [[HZCollectionView alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP oy:kMallHomeLabelHeight+self.navigationAndStatusBarHeight+20], [UBO_SCREEN fw:UB_WIDTH fh:UB_HEIGHT oh:-(kMallHomeLabelHeight+self.navigationAndStatusBarHeight+20)]) collectionViewLayout:self.layout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    [self.collectionView registerClass:[HZGoodsCategoryColCell class] forCellWithReuseIdentifier:@"HZGoodsCategoryColCell"];

    [self.collectionView registerClass:[HZGoodsCategoryColHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HZGoodsCategoryColHeadView"];
    
    
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.alwaysBounceVertical = YES;
    
    self.collectionView.nothingRefreshView = [[UIRefreshNotingRefreshView alloc] initWithView:self.collectionView viewController:self tryAgain:@selector(reloadData)];
    
    [self.view addSubview:self.collectionView];
    
    self.remoteResult = [HZRemoteResult target:self action:@selector(finishLoadData:)];
    
    [self.collectionView.nothingRefreshView showLoadingMsg:@"卖命加载中.." errorMsg:@"加载失败，点击重试"];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.navigationController.navigationBar.barTintColor = nil;
    self.navigationController.navigationBar.hidden = NO;
    
    [self loadViewData];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.barTintColor = HZ_WHITE_COLOR;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 加载数据 fill
//加载网络数据
- (void)loadViewData{
    if (self.data == nil) {
        [self reloadData];
    }else{
        
        /** 检测是否超时 或者 URL更改  -wirte by khzliu */
        CGFloat time = ([NSDate date].timeIntervalSince1970-[[[SNBaseInfoManager shareManager] baseInfoObjectForKey:kHZTimeOffsetBetweenServerAndLocal] floatValue] - [self.data.timestamp floatValue]);
        
        if (time >= kMallHotKeyWordsDataCacheValidableTime) {
            [self loadCategoryPageData];
        }
    }
}
- (void)reloadData{
    if ([SNUniteUrl shareUniteUrl].static_catogarypageUrl) {
        [self.collectionView.nothingRefreshView showLoadingMsg:@"卖命加载中.." errorMsg:@"加载失败，点击重试"];
        self.notingViewActiveStop = NO;
        [self loadCategoryPageData];
    }else{
        if (self.notingViewActiveStop) {
            [self.collectionView.nothingRefreshView showLoadingMsg:@"卖命加载中.." errorMsg:@"加载失败，点击重试"];
        }
        self.notingViewActiveStop = NO;
    }
}

#pragma mark - 收到 baseUrl 请求的次数超过默认值的通知
- (void)activityShouldStop
{
    self.notingViewActiveStop = YES;
    [self.collectionView.nothingRefreshView activeStop];
}

#pragma mark 加载数据
- (void)loadCategoryPageData{
    
    HZMallHttpManager *httpManger = [HZMallHttpManager shareHttpRequestMananger];
    [httpManger loadFindGoodsCategoriesWithParams:nil result:self.remoteResult];
}

#pragma mark 点击搜索
- (void)searchViewOnClick{
    HZMallSearchViewController *mallSrcVC = [[HZMallSearchViewController alloc] init];
    mallSrcVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mallSrcVC animated:NO];
}

#pragma mark 点击语音搜索
- (void)voiceBtnOnClick{
    SNWXVoiceTestViewController * wxVoiceVC = [[SNWXVoiceTestViewController alloc] init];
    wxVoiceVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:wxVoiceVC animated:YES];
}
#pragma mark 完成加载数据
- (void)finishLoadData:(HZRemoteResult *)result{
   
    self.data = self.remoteResult.info;

    if (self.data) {
        [self.collectionView.nothingRefreshView remove];
        [self.categoriesBar showCategories:self.data.columDetailArray];
        [UIView animateWithDuration:0.5f animations:^{
            self.collectionView.frame = CGRectOf([self.ubo fx:UB_LEFT ux:kGoodsFindCategoriesBarWidth fy:UB_TOP oy:kMallHomeLabelHeight+self.navigationAndStatusBarHeight+20], [UBO_SCREEN fw:UB_WIDTH uw:-kGoodsFindCategoriesBarWidth fh:UB_HEIGHT oh:-(kMallHomeLabelHeight+self.navigationAndStatusBarHeight+20)]);
        }];
        
    }else{
        
        [self.collectionView.nothingRefreshView activeStop];
    }
    
    self.notingViewActiveStop = YES;

}

#pragma mark 返回
- (void)backBtnClick{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 切换商品分类
- (void)switchGoodsCategory:(HZFindCategoryModel *)category{
    self.data.currentCategory = category;
    [self.collectionView reloadData];
    
    [self.collectionView setContentOffset:CGPointMake(0, 0)];
}


#pragma mark UICollectionViewDelegate UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.data.currentCategory.levelsArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HZGoodsCategoryColCell *cell = [HZGoodsCategoryColCell cellWithCollectionView:(HZCollectionView *)collectionView forIndexPath:indexPath];
    HZFindCategoryColCellModel *cellModel =[self.data.currentCategory.levelsArray objectAtIndex:indexPath.row];
    [cell displayWith:cellModel];
    return cell;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:NO];

    HZFindCategoryColCellModel *cellModel =[self.data.currentCategory.levelsArray objectAtIndex:indexPath.row];
    
    //跳到分类商品列表页面
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = HZ_WHITE_COLOR;
    
    HZMallGoodsTemaiListViewController *mallGoodsListVC = [[HZMallGoodsTemaiListViewController alloc] init];
    mallGoodsListVC.actID = cellModel.kindID;
    mallGoodsListVC.actName = cellModel.name;
    mallGoodsListVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:mallGoodsListVC animated:YES];
}


@end


